@echo off

REM PHP Version Manage By PGcao(pgcao@qq.com)
REM v1.0.1 git https://gitee.com/pgcao/pv
REM Enable delay variable extension
setlocal enabledelayedexpansion

:: Default PHP version(you can edit)
SET PHP_VER=7.2.34

:: Get the file path
SET "_PV_BAT_DIR_=%~dp0"

:: Retrieve the user-specified version number (taking only the first parameter value occurrence)
SET "phpver="
:parse
if "%~1"=="" (
	if defined phpver (
		goto done
	) else (
		goto default
	)
)
if "%~1"=="-u" (
    shift
	if defined phpver goto done
	if "%~2"=="" goto default
	SET "phpver=%~2"
)
shift
goto parse
:default
SET "phpver=%PHP_VER%"

:done
:: Get user command line parameters
SET "_PV_CLI_ARGV_=%*"

:: To clean the string for switching PHP versions
SET "clearvar=-u %phpver%"

:: Get the command line parameters for the final PHP execution
echo %_PV_CLI_ARGV_% | findstr /i "\-u" >nul
if %errorlevel%==0 (
	SET "_PV_CLI_ARGV_=!_PV_CLI_ARGV_:%clearvar% =!"
	SET "_PV_CLI_ARGV_=!_PV_CLI_ARGV_:%clearvar%=!"
)

:: Check the existence of the PHP version file
SET "PHP_PATH=%_PV_BAT_DIR_%version/php-%phpver%"
if exist "%PHP_PATH%/php.exe" (
	goto phpRun
) else (
	goto phpStop
)

:: Exit command
:phpStop
echo None existent PHP version
pause

:: Terminate the current batch script without closing the CMD window.
exit /b

:: Execution command
:phpRun
SET PATH=%PHP_PATH%;%PATH%
SET "PHP_VER="
SET "PHP_PATH="
SET "clearvar="
SET "phpver="

if not defined _PHP_HAS_USE_VERSION_ (
	@REM Run Files
	SET "_PHP_HAS_USE_VERSION_="
	@php !_PV_CLI_ARGV_!
) else (
	@REM Run Composer
	SET "_PHP_HAS_USE_VERSION_="
	if exist "%_PV_BAT_DIR_%version/composer/composer.phar" (
		@php "%_PV_BAT_DIR_%version/composer/composer.phar" !_PV_CLI_ARGV_!
	) else (
		echo None existent ./version/composer/composer.phar
		pause
	)
)
